﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
//using HalconLib;
using CommonTools;
using UserCtrl;
using MotionIoLib;
using System.Threading.Tasks;
using System.Diagnostics;
using BaseDll;
using UserData;
using System.IO;
using System.Windows.Forms.DataVisualization.Charting;
using AlgorithmNamespace;
using OtherDevice;
using System.Drawing.Imaging;
using HY_Common;
using LogType = UserData.LogType;
using ModuleCapture;
using UserData;
using Sunny.UI;
namespace StationDemo
{
    public partial class Form_Auto : UIPage
    {
        public Form_Auto()
        {
            InitializeComponent();
        }

        #region 变量
        public delegate void ShowWhiteImgDelete(Bitmap bitmap, string strSaveImgpath = "");
        public static ShowWhiteImgDelete EvenShowWhiteImgDelegate;
        public delegate void SNShowEventHandle(int n_Type,string strSN);
        public static SNShowEventHandle EvenShowSN;
        public delegate void ShowStepdelegate(string socketr, string value, LogType logType);
        public static ShowStepdelegate EventShow_设备状态;
        public static ShowStepdelegate EventShow_工站信息;
        public delegate void ShowLogdelegate(string stationName, string value, LogType logType = LogType.Info);
        public static ShowLogdelegate EventShowLog;
        public delegate void ShowNeedledelegate();
        public static ShowNeedledelegate OnShowNeedle;
        public delegate void ShowCTDelegate(int n_治具编号);
        public static ShowCTDelegate EvenShowCT;
        public delegate void SaveDispImagedelegate(string SaveImagePath);
        public static SaveDispImagedelegate _SaveDispImagedelegate;
        static Bitmap ImageSave = null;
        RunLoggeHelp log_Plasma = new RunLoggeHelp();
        RunLoggeHelp log_Disp = new RunLoggeHelp();
        RunLoggeHelp log_AA = new RunLoggeHelp();

        #endregion

        #region 事件
        private void EvenAdd()
        {
            EvenShowWhiteImgDelegate += UpdateWhiteImgChart;
            EvenShowSN += ShowSN;
            EvenShowCT += ShowCT;
            EventShow_设备状态 += ShowResultText;
            EventShow_工站信息 += ShowStationResult;
            EventShowLog += ShowLogText;
            OnShowNeedle += ShowNeedle;
            _SaveDispImagedelegate += SaveDispImage;
            Line_LoadAndUnload.OnTest_物料需求 += Line_LoadAndUnload_OnTest_物料需求;
            Line_DispBackLine.OnTest_载具需求 += Line_DispBackLine_OnTest_载具需求;
        }
        public void ShowNeedle()
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action(() => { ShowNeedle(); }));
            }
            else
            {
                try
                {
                    int nAllCount = ParamSetMgr.GetInstance().GetIntParam("点胶底座探针使用次数");
                    int nAlreadyUsedCount = LifeDetection.GetInstance().lifeData.nDispPinUsingCount;
                    int nRemain = nAllCount - nAlreadyUsedCount;
                    if (nRemain < 0)
                        nRemain = 0;
                    int g = (int)(100 * ((nRemain * 1.0) / (nAllCount * 1.0)));
                    Pgb_DispPin.Value = g < 0 ? 0 : g;
                    if (g < 2)
                    {
                        lbl_DispPinRemain.BackColor = Color.Red;
                        Pgb_DispPin.ForeColor = Color.Red;
                    }
                    else
                    {
                        lbl_DispPinRemain.BackColor = Color.Green;
                        Pgb_DispPin.ForeColor = Color.Green;
                    }
                    lbl_DispPinRemain.Text = $"点胶探针剩余次数:{nRemain}";

                    nAllCount = ParamSetMgr.GetInstance().GetIntParam("AA底座探针使用次数");
                    nAlreadyUsedCount = LifeDetection.GetInstance().lifeData.nDispPinUsingCount;
                    nRemain = nAllCount - nAlreadyUsedCount;
                    if (nRemain < 0)
                        nRemain = 0;
                    g = (int)(100 * ((nRemain * 1.0) / (nAllCount * 1.0)));
                    Pgb_AApin.Value = g < 0 ? 0 : g;
                    if (g < 2)
                    {
                        lbl_AAPinRemain.BackColor = Color.Red;
                        Pgb_AApin.ForeColor = Color.Red;
                    }
                    else
                    {
                        lbl_AAPinRemain.BackColor = Color.Green;
                        Pgb_AApin.ForeColor = Color.Green;
                    }
                    lbl_AAPinRemain.Text = $"AA探针剩余次数:{nRemain}";
                    LifeDetection.GetInstance().Save();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

        }
        private void Line_DispBackLine_OnTest_载具需求(int n_当前物料个数)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action(() => { Line_DispBackLine_OnTest_载具需求(n_当前物料个数); }));
            }
            else
            {
                btn_上载具.Visible = true;
                lb_载具个数.Visible = true;
                lb_载具个数.Text = $" 已上载具个数： {n_当前物料个数}";
            }
        }

        private void Line_LoadAndUnload_OnTest_物料需求()
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action(() => { Line_LoadAndUnload_OnTest_物料需求(); }));
            }
            else
            {
                btn_上物料.Visible = true;

            }
        }

        public void UpdateWhiteImgChart(Bitmap img, string strSaveImgpath = "")
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() => { UpdateWhiteImgChart(img, strSaveImgpath); }));
            }
            else
            {
                if (img == null)
                {
                    try
                    {
                        Bitmap NullImage = new Bitmap(pb_白场和点胶.Image.Size.Width, pb_白场和点胶.Image.Size.Width, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                        pb_白场和点胶.Image = (Image)NullImage.Clone();

                    }
                    catch (Exception)
                    {

                    }
                    return;
                }
                else
                {
                    Bitmap bmp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.DrawImage(img, new Point(0, 0));
                    }
                    pb_白场和点胶.Image = (Image)bmp.Clone();

                    return;
                }
            }
        }

        public void ShowSN(int n_Type,string strSN)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action(() => { ShowSN(n_Type,strSN); }));
            }
            else
            {
                txt_当前SN.Text = strSN;

            }

        }
        public void ShowStationResult(string stationName, string value, LogType logType)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action(() => { ShowStationResult(stationName, value, logType); }));
            }
            else
            {
                Label label = null;
                if (stationName.Contains(Station.Plasma站.ToString()))
                    label = lbl_ShowPlasmaResult;
                else if(stationName.Contains(Station.点胶站.ToString()))
                    label = lbl_ShowDispResult;
                else if (stationName.Contains(Station.AA站.ToString()))
                    label = lbl_ShowAAResult;
                if (logType == LogType.Err)
                {
                    label.BackColor = Color.Red;
                }
                else if (logType == LogType.Info)
                {
                    label.BackColor = Color.Green;
                }
                else
                {
                    label.BackColor = Color.Yellow;
                }
                label.Text = value;

            }

        }


        public void ShowResultText(string stationName, string value, LogType logType = LogType.Info)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action(() => { ShowResultText(stationName, value, logType); }));
            }
            else
            {
                if (logType == LogType.Err)
                {
                    lbl_ShowSysResult.BackColor = Color.Red;
                }
                else if (logType == LogType.Info)
                {
                    lbl_ShowSysResult.BackColor = Color.Green;
                }
                else
                {
                    lbl_ShowSysResult.BackColor = Color.Yellow;
                }
                lbl_ShowSysResult.Text = value;
            }

        }

        public void ShowLogText(string stationName, string value, LogType logType = LogType.Info)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action(() => { ShowLogText(stationName, value, logType); }));
            }
            else
            {
                if (stationName.Contains(Station.Plasma站.ToString()))
                    log_Plasma.Write(value, logType);
                else if (stationName.Contains(Station.点胶站.ToString()))
                    log_Disp.Write(value, logType);
                else if (stationName.Contains(Station.AA站.ToString()))
                    log_AA.Write(value, logType);
            }

        }
        
        public void ShowCT(int n_治具编号)
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action(() => { ShowCT(n_治具编号); }));
            }
            else
            {
                #region 数据检查
                int totalALL = 0;
                int okALL = 0;
                int n_ColCount = DeviceData.data_ProductData.Length;
                for (int i = 0; i < n_ColCount; i++)
                {
                    
                    if (DeviceData.data_ProductData[i].Total == 0)
                    {
                        DeviceData.data_ProductData[i].WhiteTestFail = 0;
                        DeviceData.data_ProductData[i].DispFail = 0;
                        DeviceData.data_ProductData[i].OCFail = 0;
                        DeviceData.data_ProductData[i].SFRFail = 0;
                        DeviceData.data_ProductData[i].PlayFail = 0;
                        DeviceData.data_ProductData[i].TiltFail = 0;
                        DeviceData.data_ProductData[i].Pencent = 0;
                        DeviceData.data_ProductData[i].OK = 0;
                    }
                    else
                    {
                        DeviceData.data_ProductData[i].Pencent = ((DeviceData.data_ProductData[i].OK / (DeviceData.data_ProductData[i].Total * 1.0)) * 100);
                    }
                    totalALL += DeviceData.data_ProductData[i].Total;
                    okALL += DeviceData.data_ProductData[i].OK;
                }
                if (totalALL != 0)
                    DeviceData.data_ProductData[0].PencentCTAll = ((okALL) / (totalALL * 1.0)) * 100;
                else
                    DeviceData.data_ProductData[0].PencentCTAll = 0;
                #endregion
                #region 显示UPH

                float height = pb_生产数据.Height;
                float width = pb_生产数据.Width;
                int RowsCount = 1 + DeviceData.data_ProductData.Length; int ColCount = 6;
                int RowsDel = 5; int ColDel = 5;
                if (width == 0 || height == 0)
                {
                    return;
                }
                Bitmap bmp = new Bitmap((int)width, (int)height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    g.Clear(Color.White);
                    SolidBrush drawSmallBrush = new SolidBrush(Color.Black);
                    Pen pen = new Pen(Color.Black, 1);
                    for (int i = 1; i <= ColCount; i++)
                    {
                        g.DrawLine(pen, (width * i) / ColCount, 0, (width * i) / ColCount, height);
                        for (int j = 1; j < RowsCount; j++)
                        {
                            if ((i == ColCount && j != 1) || (i == ColCount - 1 && j != 1))
                            {
                                continue;
                            }
                            g.DrawLine(pen, (width * (i - 1)) / ColCount, (height * j) / RowsCount, (width * i) / ColCount, (height * j) / RowsCount);
                        }
                    }
                    g.DrawString("工位", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 0 / ColCount + ColDel, height * 0 / RowsCount + RowsDel);
                    g.DrawString("投入", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 1 / ColCount + ColDel, height * 0 / RowsCount + RowsDel);
                    g.DrawString("产出", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 2 / ColCount + ColDel, height * 0 / RowsCount + RowsDel);
                    g.DrawString("良率", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 3 / ColCount + ColDel, height * 0 / RowsCount + RowsDel);
                    g.DrawString("总良率", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 4 / ColCount + ColDel, height * 0 / RowsCount + RowsDel);
                    g.DrawString("UPH", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 5 / ColCount + ColDel, height * 0 / RowsCount + RowsDel);



                    g.DrawString($"{"总计"}", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 0 / ColCount + ColDel, height * 1 / RowsCount + RowsDel);
                    g.DrawString($"{DeviceData.data_ProductData[0].Total}", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 1 / ColCount + ColDel, height * 1 / RowsCount + RowsDel);
                    g.DrawString($"{DeviceData.data_ProductData[0].OK}", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 2 / ColCount + ColDel, height * 1 / RowsCount + RowsDel);
                    g.DrawString($"{DeviceData.data_ProductData[0].Pencent.ToString("0.00")}%", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 3 / ColCount + ColDel, height * 1 / RowsCount + RowsDel);
                    for (int i = 1; i < DeviceData.data_ProductData.Length; i++)
                    {
                        g.DrawString($"{DeviceData.data_ProductData[i].strName}", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 0 / ColCount + ColDel, height * (i + 1) / RowsCount + RowsDel);
                        g.DrawString($"{ DeviceData.data_ProductData[i].Total}", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 1 / ColCount + ColDel, height * (i + 1) / RowsCount + RowsDel);
                        g.DrawString($"{ DeviceData.data_ProductData[i].OK}", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 2 / ColCount + ColDel, height * (i + 1) / RowsCount + RowsDel);
                        g.DrawString($"{DeviceData.data_ProductData[i].Pencent.ToString("0.00")}%", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 3 / ColCount + ColDel, height * (i + 1) / RowsCount + RowsDel);

                    }
                    g.DrawString($"{DeviceData.data_ProductData[0].Pencent.ToString("0.00")}%", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 4 / ColCount + ColDel, (float)(height * 3.5 / RowsCount + RowsDel));
                    g.DrawString($"{DeviceData.data_ProductData[0].UPH.ToString("0.00")}", new Font("Arial", 10, FontStyle.Regular), drawSmallBrush, width * 5 / ColCount + ColDel, (float)(height * 3.5 / RowsCount + RowsDel));

                }
                pb_生产数据.Image = bmp;
                #endregion
                #region 显示不良项目 表格
                int nRowCount = DeviceData.data_ProductData.Length+1;
                if (dg_NG统计.RowCount <= 0)
                {
                    dg_NG统计.Rows.Add(nRowCount);
                }
                dg_NG统计[0, 0].Value = "白场";
                dg_NG统计[0, 1].Value = "点胶";
                dg_NG统计[0, 2].Value = "点亮";
                dg_NG统计[0, 3].Value = "OC";
                dg_NG统计[0, 4].Value = "SFR";
                dg_NG统计[0, 5].Value = "Tilt";
                dg_NG统计[0, 6].Value = "总计";
                for (int i = 1; i < DeviceData.data_ProductData.Length; i++)
                {
                    dg_NG统计[i, 0].Value = DeviceData.data_ProductData[i].WhiteTestFail;
                    dg_NG统计[i, 1].Value = DeviceData.data_ProductData[i].DispFail;
                    dg_NG统计[i, 2].Value = DeviceData.data_ProductData[i].PlayFail;
                    dg_NG统计[i, 3].Value = DeviceData.data_ProductData[i].OCFail;
                    dg_NG统计[i, 4].Value = DeviceData.data_ProductData[i].SFRFail;
                    dg_NG统计[i, 5].Value = DeviceData.data_ProductData[i].TiltFail;
                    dg_NG统计[i, 6].Value = DeviceData.data_ProductData[i].Total - DeviceData.data_ProductData[i].OK;
                }
                double[] allFail = new double[n_ColCount];
                for (int i = 1; i < DeviceData.data_ProductData.Length; i++)
                {
                    allFail[0] += DeviceData.data_ProductData[i].WhiteTestFail;
                    allFail[1] += DeviceData.data_ProductData[i].DispFail;
                    allFail[2] += DeviceData.data_ProductData[i].PlayFail;
                    allFail[3] += DeviceData.data_ProductData[i].OCFail;
                    allFail[4] += DeviceData.data_ProductData[i].SFRFail;
                    allFail[5] += DeviceData.data_ProductData[i].TiltFail;
                }
                allFail[6] = DeviceData.data_ProductData[0].Total - DeviceData.data_ProductData[0].OK;
                dg_NG统计[DeviceData.data_ProductData.Length, 0].Value = allFail[0];
                dg_NG统计[DeviceData.data_ProductData.Length, 1].Value = allFail[1];
                dg_NG统计[DeviceData.data_ProductData.Length, 2].Value = allFail[2];
                dg_NG统计[DeviceData.data_ProductData.Length, 3].Value = allFail[3];
                dg_NG统计[DeviceData.data_ProductData.Length, 4].Value = allFail[4];
                dg_NG统计[DeviceData.data_ProductData.Length, 5].Value = allFail[5];
                dg_NG统计[DeviceData.data_ProductData.Length, 6].Value = allFail[6];
                #endregion
               
                lb_PlasmaTime.Text = DeviceData.data_Time[n_治具编号].PlasmaTime.ToString("0.00");
                lb_dispTime.Text = DeviceData.data_Time[n_治具编号].DispTime.ToString("0.00");
                lb_AATime.Text = DeviceData.data_Time[n_治具编号].AATime.ToString("0.00");
                string ctPath = $"{ParamSetMgr.GetInstance().CurrentWorkDir}\\{ParamSetMgr.GetInstance().CurrentProductFile}\\ProductInfo.xml";

                ProductInfoFile.SaveCT( DeviceData.data_ProductData, ctPath);

            }

        }
        #endregion


        private void Form_Auto_Load(object sender, EventArgs e)
        {
            #region 初始化参数配置
            //事件添加
            EvenAdd();
            //读取良率信息显示
            string ctPath = $"{ParamSetMgr.GetInstance().CurrentWorkDir}\\{ParamSetMgr.GetInstance().CurrentProductFile}\\ProductInfo.xml";
            if (!File.Exists(ctPath))
                ProductInfoFile.SaveCT(DeviceData.data_ProductData, ctPath);
            if (!ProductInfoFile.ReadCT(ref DeviceData.data_ProductData, ctPath))
            {
                MessageBox.Show("产品序列化CT参数失败", "Warn", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
            }
            //专案信息加载
            label_CurrentFile.Text = "当前产品:" + ParamSetMgr.GetInstance().CurrentProductFile;
            txt_机型.Text = ParamSetMgr.GetInstance().GetStringParam("机型");
            txt_批次.Text = ParamSetMgr.GetInstance().GetStringParam("批次");
            txt_操作者.Text = ParamSetMgr.GetInstance().GetStringParam("操作者");
            txt_设备编号.Text = ParamSetMgr.GetInstance().GetStringParam("设备编号");
            txt_工站编号.Text = ParamSetMgr.GetInstance().GetStringParam("工站编号");
            //Log界面加载
            tabControl_Log.Controls.Clear();
            log_Plasma = new RunLoggeHelp();
            log_Plasma.setFilePath(@"c:/设备Log/Plasma");
            TabPage tabPage = new TabPage();
            tabPage.Text = "Plasma";
            log_Plasma.Dock = DockStyle.Fill;
            tabPage.Controls.Add((Control)log_Plasma);
            tabControl_Log.Controls.Add(tabPage);

            log_Disp = new RunLoggeHelp();
            log_Disp.setFilePath(@"c:/设备Log/Disp");
            TabPage tabPage1 = new TabPage();
            tabPage1.Text = "Disp";
            log_Disp.Dock = DockStyle.Fill;
            tabPage1.Controls.Add((Control)log_Disp);
            tabControl_Log.Controls.Add(tabPage1);


            log_AA = new RunLoggeHelp();
            log_AA.setFilePath(@"c:/设备Log/AA");
            TabPage tabPage2 = new TabPage();
            tabPage2.Text = "AA";
            log_AA.Dock = DockStyle.Fill;
            tabPage2.Controls.Add((Control)log_AA);
            tabControl_Log.Controls.Add(tabPage2);
            tabControl_Log.SelectedIndex = 0;

            #endregion

            #region AA界面加载      
            string playPath = $"{ParamSetMgr.GetInstance().CurrentWorkDir}\\{ParamSetMgr.GetInstance().CurrentProductFile}\\";
            HY_Factory.AALineMachineFactory.Ins.Init(playPath);
            HY_Factory.AALineMachineFactory.Ins.ShowData.GetIndex = (name) => {
                switch (name)
                {
                    case "A":
                        return 0;
                    case "B":
                        return 1;
                }
                return 1;
            };
            HY_Factory.AALineMachineFactory.Ins.Captrue.StopDo = (index) => {
                if (index == 0)
                {
                    IOMgr.GetInstace().WriteIoBit(IO_OUT.AA模组上电.ToString(), false);
                    Thread.Sleep(500);
                }
                else
                {
                    IOMgr.GetInstace().WriteIoBit(IO_OUT.点胶模组上电.ToString(), false);
                    Thread.Sleep(500);
                }
            };

            HY_Factory.AALineMachineFactory.Ins.Captrue.PlayExDo = (index) => {
                if (index==0)
                {
                    IOMgr.GetInstace().WriteIoBit(IO_OUT.AA模组上电.ToString (), true);
                    Thread.Sleep(500);
                }
                else
                {
                    IOMgr.GetInstace().WriteIoBit(IO_OUT.点胶模组上电.ToString(), true);
                    Thread.Sleep(500);
                }
            };

            HY_Factory.AALineMachineFactory.Ins.Captrue.GetData = () => {
                VI_Data vI_Data = new VI_Data();
                try
                {
                    OtherDevices.Device_程控电源.GetV(0, ref vI_Data.V1);
                    OtherDevices.Device_程控电源.GetI(0, ref vI_Data.I1);
                    OtherDevices.Device_程控电源.GetV(1, ref vI_Data.V2);
                    OtherDevices.Device_程控电源.GetI(1, ref vI_Data.I2);
                }
                catch (Exception)
                {
                }
                return vI_Data;
            };
            HY_Factory.AALineMachineFactory.Ins.Captrue.Stop(1);
            #endregion

            timer1.Interval = 100;
            timer1.Start();
            log_Plasma.Write("软件加载成功!", LogType.Info);
            log_Disp.Write("软件加载成功!", LogType.Info);
            log_AA.Write("软件加载成功!", LogType.Info);


        }
        object o_ShowVisionImage = new object();
        public async void SaveDispImage(string SaveImagePath)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() => SaveDispImage(SaveImagePath)));
            }
            else
            {
                await Task.Run(() =>
                {
                    Bitmap bitmap = null;
                    try
                    {
                        lock (o_ShowVisionImage)
                        {
                            bitmap = (Bitmap)pb_白场和点胶.Image.Clone();
                            if (bitmap == null)
                            {
                                return;
                            }
                            bitmap.Save(SaveImagePath, ImageFormat.Bmp);
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                });
            }
        }
        private void Menultem_PlayWhite_Click(object sender, EventArgs e)
        {
            RunWhite();
        }
        public async static void RunWhite()
        {
            if (GlobalVariable.g_StationState != StationState.StationStateStop)
            {
                MessageBox.Show("当前程序在运行，不允许手动点亮！请先停止", "Err", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                return;
            }
            Thread.Sleep(200);            
            Station_AA stationAA = (Station_AA)StationMgr.GetInstance().GetStation("AA站");
            Rectangle[] rectangles = new Rectangle[13];
            UserTest.ContiuneWhlie = true;
            Task task_ParaA_Grab = Task.Run(() =>
            {
                while (UserTest.ContiuneWhlie)
                {
                    if (GlobalVariable.g_StationState == StationState.StationStateRun)
                    {
                        HY_Factory.AALineMachineFactory.Ins.Captrue.Stop(0);
                        break;
                    }
                    Bitmap bt = null;
                    try
                    {
                        HY_Factory.AALineMachineFactory.Ins.Captrue.CaptureToBmpRGB(1, 1, ref bt);
                    }
                    catch
                    {
                        Form_Auto.EvenShowWhiteImgDelegate(null);
                        break;
                    }
                    try
                    {
                        ImageSave = (Bitmap)bt.Clone();
                        Form_Auto.EvenShowWhiteImgDelegate((Bitmap)bt, "");
                    }
                    catch
                    {
                        Form_Auto.EvenShowWhiteImgDelegate(null, "");
                    }
                    Thread.Sleep(150);
                    GlobelManualResetEvent.WaitOne("E");
                }
            });
            await task_ParaA_Grab;
        }
        private void MenuItem_Stop_Click(object sender, EventArgs e)
        {
            if (GlobalVariable.g_StationState != StationState.StationStateStop)
            {
                MessageBox.Show("当前程序在运行，不允许手动点亮！请先停止", "Err", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                return;
            }
            Bitmap NullImage = new Bitmap(pb_白场和点胶.Image.Size.Width, pb_白场和点胶.Image.Size.Width, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            pb_白场和点胶.Image = (Image)NullImage.Clone();
        }
        private void MenuItem_SaveImageResult_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Title = "结果图片另存";
                saveFileDialog.Filter = "Color BMP Files (*.bmp)|*.bmp|Jpeg Files (*.jpg)|*.jpg|Color TIF Files (*.tif)|*.tif";
                saveFileDialog.FilterIndex = 1;//设置默认文件类型显示顺序 
                saveFileDialog.RestoreDirectory = true; //点了保存按钮进入if (picBox1.Image != null)
                saveFileDialog.FileName = "Image";

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    //Bitmap bmp;
                    //if (PictureShow.Image != null)
                    //{
                    //    bmp = (Bitmap)PictureShow.Image.Clone();
                    //    //保存到磁盘文件
                    //    bmp.Save(saveFileDialog.FileName, ImageFormat.Bmp);
                    //    bmp.Dispose();
                    //}
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存结果图片失败，{ex}", "Warn", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
            }
        }
        private void MenuItem_SaveImageBMP_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Title = "原图另存";
                saveFileDialog.Filter = "Color BMP Files (*.bmp)|*.bmp|Jpeg Files (*.jpg)|*.jpg|Color TIF Files (*.tif)|*.tif";
                saveFileDialog.FilterIndex = 1;//设置默认文件类型显示顺序 
                saveFileDialog.RestoreDirectory = true; //点了保存按钮进入if (picBox1.Image != null)
                saveFileDialog.FileName = "Image";

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    Bitmap bmp;
                    if (ImageSave != null)
                    {
                        bmp = (Bitmap)ImageSave.Clone();
                        //保存到磁盘文件
                        bmp.Save(saveFileDialog.FileName, ImageFormat.Bmp);
                        bmp.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存原图失败，{ex}", "Warn", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
            }
        }
        private void 清除数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string ctPath = $"{ParamSetMgr.GetInstance().CurrentWorkDir}\\{ParamSetMgr.GetInstance().CurrentProductFile}\\ProductInfo.xml";
            for (int i = 0; i < DeviceData.data_ProductData.Length; i++)
            {
                DeviceData.data_ProductData[i] = new ProductData($"治具{i}");
            }
            ProductInfoFile.SaveCT(DeviceData.data_ProductData, ctPath);
            Thread.Sleep(100);
            ShowCT(0);

        }

        private void btn_修改机型_Click(object sender, EventArgs e)
        {
            string value = "";
            string desc = "请输入机型名称：".Trim();
            if (UIInputDialog.InputStringDialog(this, ref value, true, desc))
            {
                if (value != "")
                {
                    txt_机型.Text = value;
                    ParamSet param = new ParamSet();
                    ParamSetMgr.GetInstance().GetParam("Model", out param);
                    param._strParamVal = value;
                    ParamSetMgr.GetInstance().SetParam("Model", param);
                    ParamSetMgr.GetInstance().SaveParam();
                }
                else
                {
                    UIMessageBox.ShowError("请输入正确的机型");
                    return;
                }
            }

        }

        private void btn_修改批次_Click(object sender, EventArgs e)
        {
            string value = "";
            string desc = "请输入批次名称：".Trim();
            if (UIInputDialog.InputStringDialog(this, ref value, true, desc))
            {
                if (value != "")
                {
                    txt_批次.Text = value;
                    ParamSet param = new ParamSet();
                    ParamSetMgr.GetInstance().GetParam("批次", out param);
                    param._strParamVal = value;
                    ParamSetMgr.GetInstance().SetParam("批次", param);
                    ParamSetMgr.GetInstance().SaveParam();
                }
                else
                {
                    UIMessageBox.ShowError("请输入正确的批次");
                    return;
                }
            }

        }

        private void btn_修改操作者_Click(object sender, EventArgs e)
        {
            string value = "";
            string desc = "请输入操作者名称：".Trim();
            if (UIInputDialog.InputStringDialog(this, ref value, true, desc))
            {
                if (value != "")
                {
                    txt_操作者.Text = value;
                    ParamSet param = new ParamSet();
                    ParamSetMgr.GetInstance().GetParam("操作者", out param);
                    param._strParamVal = value;
                    ParamSetMgr.GetInstance().SetParam("操作者", param);
                    ParamSetMgr.GetInstance().SaveParam();
                }
                else
                {
                    UIMessageBox.ShowError("请输入正确的操作者");
                    return;
                }
            }
        }

        private void btn_修改设备编号_Click(object sender, EventArgs e)
        {
            string value = "";
            string desc = "请输入设备编号名称：".Trim();
            if (UIInputDialog.InputStringDialog(this, ref value, true, desc))
            {
                if (value != "")
                {
                    txt_设备编号.Text = value;
                    ParamSet param = new ParamSet();
                    ParamSetMgr.GetInstance().GetParam("设备编号", out param);
                    param._strParamVal = value;
                    ParamSetMgr.GetInstance().SetParam("设备编号", param);
                    ParamSetMgr.GetInstance().SaveParam();
                }
                else
                {
                    UIMessageBox.ShowError("请输入正确的设备编号");
                    return;
                }
            }
        }

        private void btn_修改工站编号_Click(object sender, EventArgs e)
        {
            string value = "";
            string desc = "请输入工站编号名称：".Trim();
            if (UIInputDialog.InputStringDialog(this, ref value, true, desc))
            {
                if (value != "")
                {
                    txt_工站编号.Text = value;
                    ParamSet param = new ParamSet();
                    ParamSetMgr.GetInstance().GetParam("工站编号", out param);
                    param._strParamVal = value;
                    ParamSetMgr.GetInstance().SetParam("工站编号", param);
                    ParamSetMgr.GetInstance().SaveParam();
                }
                else
                {
                    UIMessageBox.ShowError("请输入正确的工站编号");
                    return;
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                LineStation2 lineBase = (LineStation2)StationMgr.GetInstance().GetStation("流水线");
                lb_UpLine.Text = lineBase.LoadMaterial.GetSegState().ToString();
                lb_PlasmaLine.Text = lineBase.linePlasma.GetSegState().ToString();
                lb_DispLine.Text = lineBase.lineDisp.GetSegState().ToString();

                lb_AALine.Text = lineBase.lineAA.GetSegState().ToString();

                lb_DownLine.Text = lineBase.LineBackLayOff.GetSegState().ToString();
                lb_BackAALine.Text = lineBase.BacklineAA.GetSegState().ToString();

                lb_BackDispLine.Text = lineBase.BacklineDisp.GetSegState().ToString();

                TrayStatusData[] trayStatusDatas = TrayStatusMannage.GetInstance().GetAllTrayStatusData();

                lb_Tray6.Text = trayStatusDatas[5].trayStatus.ToString();
                lb_Tray5.Text = trayStatusDatas[4].trayStatus.ToString();
                lb_Tray4.Text = trayStatusDatas[3].trayStatus.ToString();
                lb_Tray3.Text = trayStatusDatas[2].trayStatus.ToString();
                lb_Tray2.Text = trayStatusDatas[1].trayStatus.ToString();
                lb_Tray1.Text = trayStatusDatas[0].trayStatus.ToString();

                lbl_TraySn_6.Text = trayStatusDatas[5].QRCode.ToString();
                lbl_TraySn_5.Text = trayStatusDatas[4].QRCode.ToString();
                lbl_TraySn_4.Text = trayStatusDatas[3].QRCode.ToString();
                lbl_TraySn_3.Text = trayStatusDatas[2].QRCode.ToString();
                lbl_TraySn_2.Text = trayStatusDatas[1].QRCode.ToString();
                lbl_TraySn_1.Text = trayStatusDatas[0].QRCode.ToString();

            }
            catch (Exception)
            {

            }

        }

        private void btn_上载具_Click(object sender, EventArgs e)
        {
            btn_上载具.Visible = false;
            lb_载具个数.Visible = false;
            Line_DispBackLine.b_手动上载具允许 = true;
        }

        private void btn_上物料_Click(object sender, EventArgs e)
        {
            btn_上物料.Visible = false;
            Line_LoadAndUnload.b_手动上物料许可 = true;

        }

        private void panel_SFR_Paint(object sender, PaintEventArgs e)
        {
            HY_Factory.AALineMachineFactory.Ins.ShowData.Font = this.Font;
            HY_Factory.AALineMachineFactory.Ins.ShowData.SetSize(panel_SFR.Size);
            panel_SFR.Controls.Add(HY_Factory.AALineMachineFactory.Ins.ShowData);
            ShowCT(0);
            //耗材信息
            ShowNeedle();
        }
    }
    
    
}
